package com.jcw.common;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private HttpSession session;

    @Override
    public void insertFill(MetaObject metaObject) {
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        if (BeanUtil.isNotEmpty(session.getAttribute("employee"))) {
            metaObject.setValue("createUser", session.getAttribute("employee"));
            metaObject.setValue("updateUser", session.getAttribute("employee"));
            return;
        }

        Long userId = (Long) session.getAttribute("user");
        if (userId != null) {
            metaObject.setValue("createUser", userId);
            metaObject.setValue("updateUser", userId);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long employeeId = (Long) session.getAttribute("employee");
        if (session.getAttribute("employee") != null) {
            metaObject.setValue("updateTime", LocalDateTime.now());
            metaObject.setValue("updateUser", employeeId);
            return;
        }

        Long userId = (Long) session.getAttribute("user");
        if (userId != null) {
            metaObject.setValue("updateTime", LocalDateTime.now());
            metaObject.setValue("updateUser", userId);
        }
    }
}
